package com.opac.readerhome.plugin;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.opac.readerhome.activity.QrActivity;


/**
 * This class echoes a string called from JavaScript.
 */
public class QrScan extends CordovaPlugin {
	
	public static String qrcode = "";
	
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("scan")) {
            //String message = args.getString(0);
            //this.echo(message, callbackContext);
            this.qrScan(callbackContext);
            return true;
        }
        return false;
    }

   
    private void qrScan(final CallbackContext callbackContext){
    	try {
    		Intent i=new Intent();
    		
            i.setClass(this.cordova.getActivity(), QrActivity.class);
            this.cordova.getActivity().startActivity(i);
            IntentFilter myIntentFilter = new IntentFilter();  
            myIntentFilter.addAction("OnSuccess"); 
            BroadcastReceiver receiver = new BroadcastReceiver(){

				@Override
				public void onReceive(Context context, Intent intent) {
					callbackContext.success(intent.getExtras().getString("qrcode"));
					cordova.getActivity().unregisterReceiver(this);
				}
				
            };
            
            this.cordova.getActivity().registerReceiver(receiver, myIntentFilter);
            } catch (Exception e) {
			// TODO: handle exception
			callbackContext.error(e.getMessage());
		}
    }
}